﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using DevEx.Thanh.Class;
using DevExpress.XtraEditors;
using System.Linq;
using DevExpress.Utils;
using DevExpress.XtraGrid.Views.Grid;
using System.Collections;
using System.Xml;
using DevExpress.XtraBars.Ribbon;
using DevExpress.XtraNavBar;


namespace DevEx.QuocSy.UserControl
{
    public partial class ucQuanLyNhapXuat : DevExpress.XtraEditors.XtraUserControl
    {
        QLVTDataContext dc = new QLVTDataContext();
        RibbonForm _frmCall;
        
        private int _ID_User = GlobalVar.CurrentUser.ID_User;
        private int _ID_Kho = Convert.ToInt32(GlobalVar.CurrentUser.ID_Kho);

        public ucQuanLyNhapXuat(RibbonForm frm)
        {
            InitializeComponent();
            _frmCall = frm;
        }

        private void ucQuanLyNhapXuat_Load(object sender, EventArgs e)
        {
            gridView1.OptionsBehavior.Editable = false;
            //set editable = false để bắt event double click

            KhoiTaoDM();
            ReadOnlyDPNX();
            try {
                KhoiTaodtgPhieu();
                FormatdtgCTPhieu();
            }
            catch { }
            
            //HIỂN THỊ PHẦN TÌM KIẾM CỦA THANH
            //bind danh mục
            CViewer.BindKhoToLookupEdit(lkeKhoSearch);
            CViewer.BindTCNhapToLookupEdit(lkeTCNhap);
            CViewer.BindTCXuatToLookupEdit(lkeTCXuat);
            //Kiểm tra xem có phải là admin không
            if (GlobalVar.CurrentUser.ID_Role == (int)enumQuyenDangNhap.QuanTri)
            {
                lkeKhoSearch.Enabled = true;
            }
            else
            {
                lkeKhoSearch.Enabled = false;
                lkeKhoSearch.EditValue = GlobalVar.CurrentUser.ID_Kho;
            }
            //giấu phần tìm kiếm
            navBarControlTimKiem.Height = 50;
            navBarGroup1.Expanded = false;
        }

        public void KhoiTaoDM()
        {
            //1. Danh muc Tinh chat Nhap
            CTCNX m_TCNX = new CTCNX();
            lueTCNX.Properties.DisplayMember = "TCNX";
            lueTCNX.Properties.ValueMember = "ID_TCNX";

            lueTCNX.Properties.DataSource = m_TCNX.SelectAllRecord();
            lueTCNX.Properties.PopulateColumns();
            //lueTCNX.Properties.Columns["ID_TCNX"].Visible = false;
            //lueTCNX.Properties.Columns["IsNhap"].Visible = false;

            //2. Danh muc Kho
            CKho m_kho = new CKho();
            lueKho.Properties.DisplayMember = "Kho";
            lueKho.Properties.ValueMember = "ID_Kho";

            lueKho.Properties.DataSource = m_kho.SelectAllRecord();
            lueKho.Properties.PopulateColumns();
            //lueKho.Properties.Columns["ID_Kho"].Visible = false;
        }

        public void ReadOnlyDPNX()
        {
            txtDiaChi.Properties.ReadOnly = true;
            //txtDiaChi.BackColor = Color.Azure;

            txtDonViBan.Properties.ReadOnly = true;
            //txtDonViBan.BackColor = Color.Azure;

            txtHoaDon.Properties.ReadOnly = true;
            //txtHoaDon.BackColor = Color.Azure;

            txtSanPham.Properties.ReadOnly = true;
            txtLoaiSanPham.Properties.ReadOnly = true;
            //txtHopDong.BackColor = Color.Azure;

            txtLyDoNhap.Properties.ReadOnly = true;
            //txtLyDoNhap.BackColor = Color.Azure;

            txtSoPhieu.Properties.ReadOnly = true;
            //txtSoPhieu.BackColor = Color.Azure;

            txtNguoiGiaoNhan.Properties.ReadOnly = true;

            dtpNgayPhieu.Properties.ReadOnly = true;
            //dtpNgayPhieu.BackColor = Color.Azure;

            lueKho.Properties.ReadOnly = true;
            //lueKho.BackColor = Color.Azure;

            lueTCNX.Properties.ReadOnly = true;
            //lueTCNX.BackColor = Color.Azure;
            
        }

        public void KhoiTaodtgPhieu() 
        {
            //lọc theo kho ở đây
            IQueryable<tblDPNX> listPhieu = from p in dc.tblDPNXes
                                            select p;
            int idKho = -1;
            //Kiểm tra xem có phải là admin không
            if (GlobalVar.CurrentUser.ID_Role != (int)enumQuyenDangNhap.QuanTri)
            {
               idKho = GlobalVar.CurrentUser.ID_Kho.Value ;
            }
            if (idKho > -1)
                listPhieu = listPhieu.Where(p => p.ID_Kho == idKho);
            // het phan loc theo kho
            try {
                var q = from p in listPhieu
                        orderby p.NgayPhieu descending
                        select new
                        {
                            p.ID_DPNX,
                            p.NX,
                            SoPhieu = (Convert.ToDateTime(p.NgayPhieu).Month > 9 ?
                            Convert.ToString(p.SoPhieu) + p.ChuPhieu + p.DuoiPhieu + "/" + Convert.ToDateTime(p.NgayPhieu).Month.ToString() + "-" + Convert.ToDateTime(p.NgayPhieu).Year.ToString().Substring(2, 2)
                            : Convert.ToString(p.SoPhieu) + p.ChuPhieu + p.DuoiPhieu + "/0" + Convert.ToDateTime(p.NgayPhieu).Month.ToString() + "-" + Convert.ToDateTime(p.NgayPhieu).Year.ToString().Substring(2, 2)),
                            p.NgayPhieu,
                            p.TongGiaTri,
                            p.ID_ApproveUser
                        }
                        ;

                dtgPhieu.DataSource = q;
                FormatdtgPhieu();
            }
            catch { }
            
        }

        public void FormatdtgPhieu()
        {            
            gridView1.Columns.ColumnByFieldName("ID_DPNX").Visible = false;
            gridView1.Columns.ColumnByFieldName("ID_ApproveUser").Visible = false;
                        
            //Columns NX
            var cl_NX = gridView1.Columns.ColumnByFieldName("NX");
            cl_NX.Width = 20;
            cl_NX.Caption = "NX";
            cl_NX.OptionsColumn.AllowEdit = false;
            cl_NX.AppearanceCell.TextOptions.HAlignment = HorzAlignment.Center;
            cl_NX.AppearanceHeader.TextOptions.HAlignment = HorzAlignment.Center;

            //Columns SoPhieu
            var cl_SoPhieu = gridView1.Columns.ColumnByFieldName("SoPhieu");
            cl_SoPhieu.Width = 70;
            cl_SoPhieu.Caption = "Số phiếu";
            cl_SoPhieu.OptionsColumn.AllowEdit = false;
            cl_SoPhieu.AppearanceCell.TextOptions.HAlignment = HorzAlignment.Center;
            cl_SoPhieu.AppearanceHeader.TextOptions.HAlignment = HorzAlignment.Center;

            //Columns NgayPhieu
            var cl_NgayPhieu = gridView1.Columns.ColumnByFieldName("NgayPhieu");
            cl_NgayPhieu.Width = 70;
            cl_NgayPhieu.Caption = "Ngày";
            cl_NgayPhieu.OptionsColumn.AllowEdit = false;cl_NgayPhieu.AppearanceCell.TextOptions.HAlignment = HorzAlignment.Center;
            cl_NgayPhieu.AppearanceHeader.TextOptions.HAlignment = HorzAlignment.Center;
            //cl_NgayPhieu.DisplayFormat.FormatString = "dd/MM/yyyy";

            //Columns TongGiaTri
            var cl_TongGiaTri = gridView1.Columns.ColumnByFieldName("TongGiaTri");
            //cl_TongGiaTri.Width = 70;
            cl_TongGiaTri.Caption = "Tổng tiền";
            cl_TongGiaTri.OptionsColumn.AllowEdit = false;
            cl_TongGiaTri.AppearanceCell.TextOptions.HAlignment = HorzAlignment.Far;
            cl_TongGiaTri.AppearanceHeader.TextOptions.HAlignment = HorzAlignment.Center;
            cl_TongGiaTri.DisplayFormat.FormatType = DevExpress.Utils.FormatType.Numeric;
            cl_TongGiaTri.DisplayFormat.FormatString = "n0";
            
        }

        private void gridView1_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            if (e.FocusedRowHandle >= 0)
            {
                int ID_DPNX = Convert.ToInt32(gridView1.GetFocusedRowCellValue("ID_DPNX"));
                KhoiTaodtgCTPhieu(ID_DPNX);

                // Change label N,X
                String NX = gridView1.GetFocusedRowCellValue("NX").ToString();
                if (NX == "N")
                {
                    lblPhieuNhapXuat.Text = "PHIẾU NHẬP";
                    lblDonVi.Text = "Đơn vị bán";
                    lblHoaDon.Text = "Số hóa đơn";
                    lblKho.Text = "Kho Nhập";
                    lblLyDoNhapXuat.Text = "Lý do Nhập";
                    lblSoPhieu.Appearance.ForeColor = Color.LimeGreen;
                    lblPhieuNhapXuat.Appearance.ForeColor = Color.LimeGreen;
                    txtSoPhieu.ForeColor = Color.LimeGreen;
                    lblNguoiLapPhieu.ForeColor = Color.LimeGreen;
                    lblNguoiXacNhan.ForeColor = Color.LimeGreen;
                    lblTCNX.Text = "Tính chất Nhập";
                    lblNguoiGiaoNhan.Text = "Người nhận hàng";
                }
                else if (NX == "X")
                {
                    lblPhieuNhapXuat.Text = "PHIẾU XUẤT";
                    lblDonVi.Text = "Đơn vị nhận";
                    lblHoaDon.Text = "Số phương án";
                    lblKho.Text = "Kho Xuất";
                    lblLyDoNhapXuat.Text = "Lý do Xuất";
                    lblSoPhieu.Appearance.ForeColor = Color.Red;
                    lblPhieuNhapXuat.Appearance.ForeColor = Color.Red;
                    txtSoPhieu.ForeColor = Color.Red;
                    lblNguoiLapPhieu.ForeColor = Color.Red;
                    lblNguoiXacNhan.ForeColor = Color.Red;
                    lblTCNX.Text = "Tính chất Xuất";
                    lblNguoiGiaoNhan.Text = "Người giao hàng";
                }

            }
            
        }
                
        public void KhoiTaodtgCTPhieu(int ID_DPNX)
        {
            //1. DPNX
            CDPNX m_DPNX = new CDPNX();
            
            var DPNX = m_DPNX.SelectRecordByID(ID_DPNX);

            CModule_Sy module = new CModule_Sy();
            txtSoPhieu.EditValue = module.GetSoPhieu(ID_DPNX);

            //if (Convert.ToDateTime(DPNX.NgayPhieu).Month > 9)
            //{
            //    txtSoPhieu.EditValue = DPNX.SoPhieu.ToString() + "/" + Convert.ToDateTime(DPNX.NgayPhieu).Month.ToString() + Convert.ToDateTime(DPNX.NgayPhieu).Year.ToString().Substring(2, 2);
            //}
            //else
            //{
            //    txtSoPhieu.EditValue = DPNX.SoPhieu.ToString() + "/0" + Convert.ToDateTime(DPNX.NgayPhieu).Month.ToString() + Convert.ToDateTime(DPNX.NgayPhieu).Year.ToString().Substring(2, 2);
            //}
                
            dtpNgayPhieu.EditValue = DPNX.NgayPhieu;
            lueTCNX.EditValue = DPNX.ID_TCNX;
            lueKho.EditValue = DPNX.ID_Kho;
            txtLyDoNhap.EditValue = DPNX.LyDoNhapXuat;
            txtDonViBan.EditValue = DPNX.tblDonVi.DonVi;
            txtDiaChi.EditValue = DPNX.tblDonVi.DiaChi;
            txtHoaDon.EditValue = DPNX.HoaDon;
            txtNguoiGiaoNhan.EditValue = DPNX.NguoiGiaoNhan;
            lblNguoiLapPhieu.Text = "Người lập phiếu: " + DPNX.tblUser.FullName;
            if (DPNX.ID_ApproveUser == null)
                lblNguoiXacNhan.Text = "Người xác nhận: ";
            else
                lblNguoiXacNhan.Text = "Người xác nhận: " + DPNX.tblUser1.FullName??"";

            if (DPNX.NX == "X" && DPNX.ID_TCNX == 8)// Xuất sửa chữa
            {
                lblSanPham.Visible = true;
                txtSanPham.Visible = true;
                lblLoaiSanPham.Visible = true;
                txtLoaiSanPham.Visible = true;
                if (DPNX.tblSanPham .SanPham == null)
                {
                    txtSanPham.Text = "";
                    txtLoaiSanPham.Text = "";
                }                    
                else
                {
                    txtSanPham.Text = DPNX.tblSanPham.SanPham;
                    CSanPham m_sanpham = new CSanPham();                    
                    int ID = Convert.ToInt32(m_sanpham.SelectRecordByID(Convert.ToInt32(DPNX.ID_SanPham)).ID_Parent);                     
                    txtLoaiSanPham.Text = m_sanpham.SelectRecordByID(ID).SanPham;
                }               
            }
            else if (DPNX.NX == "X" && DPNX.ID_TCNX == 7)// Xuất sản phẩm
            {
                lblSanPham.Visible = false;
                txtSanPham.Visible = false;
                lblLoaiSanPham.Visible = true;
                txtLoaiSanPham.Visible = true;
                if (DPNX.tblSanPham.SanPham == null)
                {
                    txtSanPham.Text = "";
                    txtLoaiSanPham.Text = "";
                }                    
                else
                {
                    txtLoaiSanPham.Text = DPNX.tblSanPham.SanPham;                    
                }               
            }
            else
            {
                lblSanPham.Visible = false;
                txtSanPham.Visible = false;
                lblLoaiSanPham.Visible = false;
                txtLoaiSanPham.Visible = false;
            }


            //2. CTNX
            var q = from p in dc.tblSLNXes
                    where p.ID_DPNX == ID_DPNX
                    select new 
                    { 
                        p.tblTon.tblVatTu.VatTu,
                        p.tblTon.tblVatTu.MaKyHieu,
                        p.tblTon.NamSX,
                        p.tblTon.tblCCL.CCL,                        
                        p.tblTon.Gia,                        
                        p.SLKH,
                        p.ThanhTien,
                        p.tblTon.tblNguonVatTu.KH_NguonVatTu,
                        p.tblTon.tblHopDong.SoHopDong,
                        SoTheKho = p.tblTon.SoTheKho + "-" + Convert.ToString(p.tblTon.Code),                        
                        p.tblTon.TangKeKhoang
                    };

            dtgChiTietPhieu.DataSource = q;
            //FormatdtgCTPhieu();
        }

        public void FormatdtgCTPhieu() 
        {            
            //gridView2.Columns.ColumnByFieldName("ID_MatHang").Visible = false;
            gridView2.OptionsView.ShowFooter = true;
            //Columns VatTu
            var cl_VatTu = gridView2.Columns.ColumnByFieldName("VatTu");
            cl_VatTu.Width = 120;
            cl_VatTu.Caption = "Vật Tư";
            cl_VatTu.AppearanceCell.TextOptions.HAlignment = HorzAlignment.Near;
            cl_VatTu.OptionsColumn.AllowEdit = false;
            cl_VatTu.AppearanceHeader.TextOptions.HAlignment = HorzAlignment.Center;

            //Columns CCL
            var cl_CCL = gridView2.Columns.ColumnByFieldName("CCL");
            cl_CCL.Width = 40;
            cl_CCL.OptionsColumn.AllowEdit = false;
            cl_CCL.Caption = "CCL";
            cl_CCL.AppearanceCell.TextOptions.HAlignment = HorzAlignment.Center;
            cl_CCL.AppearanceHeader.TextOptions.HAlignment = HorzAlignment.Center;

            //Columns Nguon Tai Chinh
            var cl_NguonVatTu = gridView2.Columns.ColumnByFieldName("KH_NguonVatTu");
            cl_NguonVatTu.Width = 40;
            cl_NguonVatTu.OptionsColumn.AllowEdit = false;
            cl_NguonVatTu.Caption = "N. TC";
            cl_NguonVatTu.AppearanceCell.TextOptions.HAlignment = HorzAlignment.Center;
            cl_NguonVatTu.AppearanceHeader.TextOptions.HAlignment = HorzAlignment.Center;

            //Columns Nguon Nhap
            var cl_NguonNhap = gridView2.Columns.ColumnByFieldName("SoHopDong");
            cl_NguonNhap.Width = 70;
            cl_NguonNhap.OptionsColumn.AllowEdit = false;
            cl_NguonNhap.Caption = "Nguồn gốc";
            cl_NguonNhap.AppearanceCell.TextOptions.HAlignment = HorzAlignment.Near;
            cl_NguonNhap.AppearanceHeader.TextOptions.HAlignment = HorzAlignment.Center;
            
            //Columns NamSX
            var cl_NamSX = gridView2.Columns.ColumnByFieldName("NamSX");
            cl_NamSX.Width = 50;
            cl_NamSX.OptionsColumn.AllowEdit = false;
            cl_NamSX.Caption = "Năm SX";
            cl_NamSX.AppearanceCell.TextOptions.HAlignment = HorzAlignment.Center;
            cl_NamSX.AppearanceHeader.TextOptions.HAlignment = HorzAlignment.Center;

            //Columns MaKyHieu
            var cl_MaKyHieu = gridView2.Columns.ColumnByFieldName("MaKyHieu");
            cl_MaKyHieu.Caption = "Mã Hiệu";
            cl_MaKyHieu.OptionsColumn.AllowEdit = false;
            cl_MaKyHieu.AppearanceCell.TextOptions.HAlignment = HorzAlignment.Near;
            cl_MaKyHieu.AppearanceHeader.TextOptions.HAlignment = HorzAlignment.Center;

            //Columns SoTheKho
            var cl_SoTheKho = gridView2.Columns.ColumnByFieldName("SoTheKho");
            cl_SoTheKho.Width = 70;
            cl_SoTheKho.Caption = "Thẻ Kho";
            cl_SoTheKho.OptionsColumn.AllowEdit = false;
            cl_SoTheKho.AppearanceCell.TextOptions.HAlignment = HorzAlignment.Center;
            cl_SoTheKho.AppearanceHeader.TextOptions.HAlignment = HorzAlignment.Center;

            ////Columns SoTheKho
            //var cl_Code = gridView2.Columns.ColumnByFieldName("Code");
            //cl_Code.Width = 30;
            //cl_Code.Caption = "Code";
            //cl_Code.OptionsColumn.AllowEdit = false;
            //cl_Code.AppearanceCell.TextOptions.HAlignment = HorzAlignment.Center;
            //cl_Code.AppearanceHeader.TextOptions.HAlignment = HorzAlignment.Center;

            //Columns TangKeKhoang
            var cl_TangKeKhoang = gridView2.Columns.ColumnByFieldName("TangKeKhoang");
            cl_TangKeKhoang.Width = 40;
            cl_TangKeKhoang.OptionsColumn.AllowEdit = false;
            cl_TangKeKhoang.Caption = "Vị trí";
            cl_TangKeKhoang.AppearanceCell.TextOptions.HAlignment = HorzAlignment.Center;
            cl_TangKeKhoang.AppearanceHeader.TextOptions.HAlignment = HorzAlignment.Center;

            //Columns Gia
            var cl_Gia = gridView2.Columns.ColumnByFieldName("Gia");
            cl_Gia.Width = 70;
            cl_Gia.OptionsColumn.AllowEdit = false;
            cl_Gia.Caption = "Đơn giá";
            cl_Gia.AppearanceCell.TextOptions.HAlignment = HorzAlignment.Far;
            cl_Gia.AppearanceHeader.TextOptions.HAlignment = HorzAlignment.Center;
            cl_Gia.DisplayFormat.FormatType = DevExpress.Utils.FormatType.Numeric;
            cl_Gia.DisplayFormat.FormatString = "n0";

            //Columns ThanhTien
            var cl_ThanhTien = gridView2.Columns.ColumnByFieldName("ThanhTien");
            cl_ThanhTien.Width = 90;
            cl_ThanhTien.Caption = "Thành tiền";
            cl_ThanhTien.OptionsColumn.AllowEdit = false;
            cl_ThanhTien.AppearanceCell.TextOptions.HAlignment = HorzAlignment.Far;
            cl_ThanhTien.AppearanceHeader.TextOptions.HAlignment = HorzAlignment.Center;
            cl_ThanhTien.DisplayFormat.FormatType = DevExpress.Utils.FormatType.Numeric;
            cl_ThanhTien.DisplayFormat.FormatString = "n0";
            cl_ThanhTien.Summary.Add(DevExpress.Data.SummaryItemType.Sum, "ThanhTien", "{0:n0}");

         
            //Columns SLTonKH
            var cl_SLTonKH = gridView2.Columns.ColumnByFieldName("SLKH");
            cl_SLTonKH.Width = 60;
            cl_SLTonKH.OptionsColumn.AllowEdit = false;
            cl_SLTonKH.Caption = "SLKH";
            cl_SLTonKH.AppearanceCell.TextOptions.HAlignment = HorzAlignment.Far;
            cl_SLTonKH.AppearanceHeader.TextOptions.HAlignment = HorzAlignment.Center;
            cl_SLTonKH.DisplayFormat.FormatType = DevExpress.Utils.FormatType.Numeric;
            cl_SLTonKH.DisplayFormat.FormatString = "n0";
        }

        private void gridView2_CustomDrawRowFooterCell(object sender, FooterCellCustomDrawEventArgs e)
        {
            ////e.Appearance.BackColor = Color.Red;
            ////Change the background color
            //if (gridView1.GetFocusedRowCellValue("NX").ToString() == "N")
            //{
            //    e.Appearance.BackColor = Color.LimeGreen;
            //}
            //else
            //{
            //    e.Appearance.BackColor = Color.Red;
            //}
            
            ////Font f = new Font(e.Appearance.Font.Name, 10, FontStyle.Bold);
            ////e.Appearance.Font = f;
            ////Paint using the new background color
            //e.Painter.DrawObject(e.Info);
            ////Prevent default painting
            //e.Handled = true;
        }

        private void gridView1_RowStyle(object sender, RowStyleEventArgs e)
        {
            if (e.RowHandle >= 0)
            {
                int ID_ApproveUser = 0;
                try
                { ID_ApproveUser = Convert.ToInt32(gridView1.GetRowCellValue(e.RowHandle, gridView1.Columns["ID_ApproveUser"])); }
                catch {}

                if (ID_ApproveUser > 0)//Is_Approve
                {
                    e.Appearance.ForeColor = Color.Blue;
                    //e.Appearance.BackColor = Color.Blue;
                    //e.Appearance.BackColor2 = Color.SeaShell;
                    e.Appearance.Font = new Font(e.Appearance.Font, FontStyle.Bold);
                }
                //else
                //{
                //    //e.Appearance.BackColor = Color.MediumSpringGreen;
                //    //e.Appearance.BackColor2 = Color.SeaShell;
                //    //e.Appearance.ForeColor = Color.Blue;
                //    //e.Appearance.Font = new Font(e.Appearance.Font, FontStyle.Italic);
                //}                
            }
        }

        private void dtgPhieu_DoubleClick(object sender, EventArgs e)
        {
            int ID_DPNX = Convert.ToInt32(gridView1.GetFocusedRowCellValue("ID_DPNX"));
            CDPNX m_DPNX = new CDPNX();
            tblDPNX obj_DPNX = m_DPNX.SelectRecordByID(ID_DPNX);
            if (obj_DPNX.ID_CreatedUser == _ID_User)
            {
                if(obj_DPNX.ID_ApproveUser != null)
                {
                    MessageBox.Show("Phiếu đã xác nhận. Hủy xác nhận để cập nhật phiếu");
                    return;
                }
                String NX = gridView1.GetFocusedRowCellValue("NX").ToString();
                String SoPhieu = gridView1.GetFocusedRowCellValue("SoPhieu").ToString();

                var listPhieuNhap = from p in dc.tblCKNBs 
                                    select p.ID_PhieuNhap;
                var listPhieuXuat = from p in dc.tblCKNBs 
                                    select p.ID_PhieuXuat;


                int exist_CKNB = (from p in dc.tblCKNBs
                                  where listPhieuNhap.Contains(ID_DPNX) || listPhieuXuat.Contains(ID_DPNX)
                                  select p).Count();

                if (exist_CKNB > 0)
                {
                    ((frmMain)_frmCall).AddTabPhieuCKNB(NX, ID_DPNX);
                }
                else
                {
                    ((frmMain)_frmCall).AddTabPhieuNhapXuat(NX, ID_DPNX, SoPhieu);
                }

                
            }
            else { MessageBox.Show("Bạn không phải người lập phiếu"); }
        }

        private void navBarControlTimKiem_MouseUp(object sender, MouseEventArgs e)
        {
            try
            {
                if (e.Button == MouseButtons.Left)
                {

                    NavBarHitInfo info = (sender as NavBarControl).CalcHitInfo(new Point(e.X, e.Y));

                    if (!info.Group.Expanded)
                    {

                        //Expand
                        navBarControlTimKiem.Height = 438;

                    }
                    else
                    {
                        navBarControlTimKiem.Height = 50;
                    }
                }
            }
            catch { };
        }

        private void btnTimKiem_Click_1(object sender, EventArgs e)
        {
            string soPhieu = txtSoPhieuSearch.Text;
            DateTime ngayPhieuTu= DateTime.MinValue;
            DateTime ngayPhieuDen = DateTime.MinValue;
            if (dateNgayPhieuTu.Text !="")
                ngayPhieuTu =  Convert.ToDateTime( dateNgayPhieuTu.EditValue) ;
            if (dateNgayPhieuDen.Text != "")
                ngayPhieuDen = Convert.ToDateTime(dateNgayPhieuDen.EditValue);
            int tinhChatNhapXuatID = -1;
            if (lkeTCNhap.EditValue != null)
                tinhChatNhapXuatID = Convert.ToInt32(lkeTCNhap.EditValue);
            if (lkeTCXuat.EditValue != null)
                tinhChatNhapXuatID = Convert.ToInt32(lkeTCXuat.EditValue);
            int khoNhapXuatID = Convert.ToInt32(lkeKhoSearch.EditValue);
            string sanPham = txtSanPhamSearch.Text;
            double  soTienTu = double.MinValue;
            if (txtSoTienTuSearch.Text !="")
                soTienTu = Convert.ToDouble( txtSoTienTuSearch .Text );
            double soTienDen = double.MaxValue;
            if (txtSoTienDenSearch .Text !="")
                soTienDen = Convert.ToDouble(txtSoTienDenSearch.Text);
            string lyDo = txtLyDoSearch.Text;
            string donVi = txtDonViSearch.Text;
            string hoaDon = txtHoaDonSearch.Text;
            string tenVatTu = txtTenVatTuSearch.Text;
            string kyMaHieu = txtKyMaHieuSearch.Text;
            string nguonTC = txtNguonTCSearch .Text ;
            string nguonNhap = txtNguonNhapSearch.Text;
            var q = LocDanhSachPhieu(soPhieu, ngayPhieuTu, ngayPhieuDen , tinhChatNhapXuatID, khoNhapXuatID, sanPham, soTienTu, soTienDen, lyDo, donVi, hoaDon,
                                                    tenVatTu, kyMaHieu, nguonTC, nguonNhap);
            dtgPhieu.DataSource = q;
            FormatdtgPhieu();
            //giấu phần tìm kiếm
            navBarControlTimKiem.Height = 50;
            navBarGroup1.Expanded = false;
        }

        public IQueryable LocDanhSachPhieu(string soPhieu, DateTime ngayPhieuTu, DateTime ngayPhieuDen, int tinhChatNhapXuatID, int khoNhapXuatID,
                                                    string sanPham, double  soTienTu, double  soTienDen, string lyDo, string donVi, string hoaDon,
                                                    string tenVatTu, string kyMaHieu, string nguonTC, string nguonNhap)
        {
            IQueryable<tblDPNX> listPhieu = from p in dc.tblDPNXes
                                            orderby p.NgayPhieu descending
                                            select p;
            //lọc theo kho ở đây
            if (lkeKhoSearch.EditValue!=null )
            {
                int khoID = Convert.ToInt32(lkeKhoSearch.EditValue);
                listPhieu = listPhieu.Where(p => p.ID_Kho ==khoID );
            }
            if (soPhieu !="")
            {
                listPhieu = listPhieu.Where(p => p.SoPhieu == Convert.ToInt32(soPhieu));
            }
            if (ngayPhieuTu!=DateTime.MinValue )
            {
                listPhieu = listPhieu.Where(p => p.NgayPhieu >=ngayPhieuTu );
            }
            if (ngayPhieuDen != DateTime.MinValue)
            {
                listPhieu = listPhieu.Where(p => p.NgayPhieu <= ngayPhieuDen);
            }
            if (tinhChatNhapXuatID>0)
            {
                listPhieu = listPhieu.Where(p => p.ID_TCNX == tinhChatNhapXuatID);
            }
            if (khoNhapXuatID >0)
            {
                listPhieu = listPhieu.Where(p => p.ID_Kho == khoNhapXuatID);
            }
            if (sanPham!="")
            {
                listPhieu = listPhieu.Where(p => p.tblSanPham.SanPham.Contains(sanPham));
            }
            if (soTienTu!=double.MinValue )
            {
                listPhieu = listPhieu.Where(p => p.TongGiaTri >= soTienTu);
            }
            if (soTienDen != double.MinValue)
            {
                listPhieu = listPhieu.Where(p => p.TongGiaTri <= soTienDen);
            }
            if (lyDo !="")
            {
                listPhieu = listPhieu.Where(p => p.LyDoNhapXuat.Contains( lyDo));
            }
            if (donVi  != "")
            {
                listPhieu = listPhieu.Where(p => p.tblDonVi.DonVi.Contains( donVi ));
            }
            if (hoaDon !="")
            {
                listPhieu = listPhieu.Where(p => p.HoaDon.Contains( hoaDon ));
            }
            if (tenVatTu !="")
            {
                listPhieu = listPhieu.Where(p => p.tblSLNXes.Any(ct => ct.tblTon.tblVatTu.VatTu.Contains(tenVatTu)));
            }
            if (kyMaHieu != "")
            {
                listPhieu = listPhieu.Where(p => p.tblSLNXes.Any(ct => ct.tblTon.tblVatTu.MaKyHieu.Contains( kyMaHieu)));
            }
            if (nguonTC  != "")
            {
                listPhieu = listPhieu.Where(p => p.tblSLNXes.Any(ct => ct.tblTon.tblNguonVatTu.KH_NguonVatTu.ToLower().Contains( nguonTC.ToLower( ) )));
            }
            if (nguonNhap != "")
            {
                listPhieu = listPhieu.Where(p => p.tblSLNXes.Any(ct => ct.tblTon.tblHopDong.SoHopDong.ToLower().Contains(nguonNhap .ToLower())));
            }
            //dinh dang lai du lieu
            var q = from p in listPhieu
                    orderby p.NgayPhieu descending
                    select new
                    {
                        p.ID_DPNX,
                        p.NX,
                        SoPhieu = (Convert.ToDateTime(p.NgayPhieu).Month > 9 ?
                            Convert.ToString(p.SoPhieu) + p.ChuPhieu + p.DuoiPhieu + "/" + Convert.ToDateTime(p.NgayPhieu).Month.ToString() + "-" + Convert.ToDateTime(p.NgayPhieu).Year.ToString().Substring(2, 2)
                            : Convert.ToString(p.SoPhieu) + p.ChuPhieu + p.DuoiPhieu + "/0" + Convert.ToDateTime(p.NgayPhieu).Month.ToString() + "-" + Convert.ToDateTime(p.NgayPhieu).Year.ToString().Substring(2, 2)),
                        p.NgayPhieu,
                        p.TongGiaTri,
                        p.ID_ApproveUser
                    }
                    ;
            return q;
        }

        #region Kho xác nhận và hủy xác nhận phiếu

        private void khoXácNhậnPhiếuToolStripMenuItem_Click(object sender, EventArgs e)
        {
            CDPNX m_DPNX = new CDPNX();
            int ID_DPNX = Convert.ToInt32(gridView1.GetFocusedRowCellValue("ID_DPNX"));
            m_DPNX.XacNhanPhieu(ID_DPNX, _ID_User);
            btnTimKiem_Click_1(sender, e);
        }

        private void hủyXácNhậnPhiếuToolStripMenuItem_Click(object sender, EventArgs e)
        {
            CDPNX m_DPNX = new CDPNX();
            int ID_DPNX = Convert.ToInt32(gridView1.GetFocusedRowCellValue("ID_DPNX"));
            m_DPNX.HuyXacNhanPhieu(ID_DPNX, _ID_User);

            btnTimKiem_Click_1(sender, e);
        }
        #endregion

        private void cậpNhậtPhiếuToolStripMenuItem_Click(object sender, EventArgs e)
        {
            dtgPhieu_DoubleClick(sender, e);
            btnTimKiem_Click_1(sender, e);
        }

        private void inPhiếuToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void làmMớiDanhSáchToolStripMenuItem_Click(object sender, EventArgs e)
        {
            btnTimKiem_Click_1(sender, e);
        }

        private void xóaPhiếuToolStripMenuItem_Click(object sender, EventArgs e)
        {
            CDPNX m_DPNX = new CDPNX();
            int ID_DPNX = Convert.ToInt32(gridView1.GetFocusedRowCellValue("ID_DPNX"));
            var DPNX = m_DPNX.SelectRecordByID(ID_DPNX);

            // Kiểm tra phiếu đã được xác nhận chưa
            if (DPNX.ID_ApproveUser != null)
            {
                MessageBox.Show("Phiếu đã được xác nhận, hủy xác nhận trước khi xóa");
                return;
            }
            
            //Kiểm tra người lập phiếu
            if (DPNX.ID_CreatedUser == _ID_User)
            {                
                String SoPhieu = txtSoPhieu.Text;
                DialogResult dialogResult = MessageBox.Show("Bạn muốn xóa phiếu số: " + SoPhieu, "Chú ý", MessageBoxButtons.YesNo);
                if (dialogResult == DialogResult.Yes)
                {
                    //Refesh phiếu
                    m_DPNX.Delete(ID_DPNX);
                    btnTimKiem_Click_1(sender, e);
                }
                             
            }                
            else
                MessageBox.Show("Bạn không phải người lập phiếu");            
        }

        private void lkeTCNhap_EditValueChanged(object sender, EventArgs e)
        {
            if (Convert.ToInt32( lkeTCNhap.EditValue)>0)
            {
                lkeTCXuat.EditValue  = null;
            }
        }

        private void lkeTCXuat_EditValueChanged(object sender, EventArgs e)
        {
            if (Convert.ToInt32(lkeTCXuat.EditValue) >0)
            {
                lkeTCNhap.EditValue = null;
            }
        }

        private void xuấtExcelToolStripMenuItem_Click(object sender, EventArgs e)
        {
            int ID_DPNX = Convert.ToInt32(gridView1.GetFocusedRowCellValue("ID_DPNX"));
            CModule_Sy module = new CModule_Sy();
            String NX = Convert.ToString(gridView1.GetFocusedRowCellValue("NX"));
            if (NX == "N")
                module.ToExcel_PhieuNhap(ID_DPNX);
            else
                module.ToExcel_PhieuXuat(ID_DPNX);
            
        }

        private void lậpPhiếuXuấtToolStripMenuItem_Click(object sender, EventArgs e)
        {
            int ID_DPNX = Convert.ToInt32(gridView1.GetFocusedRowCellValue("ID_DPNX"));
            CDPNX m_DPNX = new CDPNX();
            tblDPNX obj_DPNX = m_DPNX.SelectRecordByID(ID_DPNX);
            String NX = obj_DPNX.NX;

            if (obj_DPNX.ID_CreatedUser == _ID_User)
            {
                if (obj_DPNX.NX == "N")
                {
                    String SoPhieu = gridView1.GetFocusedRowCellValue("SoPhieu").ToString();

                    //var listPhieuNhap = from p in dc.tblCKNBs
                    //                    select p.ID_PhieuNhap;
                    //var listPhieuXuat = from p in dc.tblCKNBs
                    //                    select p.ID_PhieuXuat;


                    //int exist_CKNB = (from p in dc.tblCKNBs
                    //                  where listPhieuNhap.Contains(ID_DPNX) || listPhieuXuat.Contains(ID_DPNX)
                    //                  select p).Count();

                    //if (exist_CKNB > 0)
                    //{
                    //    ((frmMain)_frmCall).AddTabPhieuCKNB(NX, ID_DPNX);
                    //}
                    //else
                    //{
                    ((frmMain)_frmCall).AddTabPhieuXuat(ID_DPNX);
                    //}
                }
                else { MessageBox.Show("Bạn phải chọn phiếu nhập"); }
            }
            else { MessageBox.Show("Bạn không phải người lập phiếu"); }
        }        

    }
}

